package com.ezware.cleansweep.core;

import javax.swing.SwingUtilities;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.springframework.osgi.context.BundleContextAware;

import com.ezware.cleansweep.core.internal.ApplicationMainFrame;
import com.ezware.cleansweep.core.internal.DefaultApplication;

public class Platform implements BundleContextAware {
	
	private BundleContext bundleContext;
	private IApplication app = new DefaultApplication();
	private ApplicationMainFrame frame;
	private boolean running = false;
	
	public void start() {
		
		if (running) return;
		running = true;
		
		app.initialize();
		SwingUtilities.invokeLater(  new Runnable() {
				@Override
				public void run() {
					createMainFrame();
					app.ready();
					frame.setVisible(true);
				}
			}
		 );
		
	}
	
	private void createMainFrame() {
		frame = new ApplicationMainFrame( this );
		//TODO retrieve position and size
		frame.setSize(800,600);
		frame.setLocationRelativeTo(null);
	}
	
	
	/**
	 * Shuts down the OSGi container and exits the application
	 */
	public void exit() {
		if ( app.canExit() )  {
			shutdownOsgiContainer();
			if ( frame != null ) frame.setVisible(false);
			System.exit(0);
		}
	}


	// TODO Find the standard way to shutdown the OSGi container
	private void shutdownOsgiContainer() {
		try {
			bundleContext.getBundle(0).stop();
		} catch (BundleException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}
	
	public IApplication getApplication() {
		return app;
	}
	
	public void setApplication(IApplication lifecycle) {
		this.app = lifecycle == null? new DefaultApplication(): lifecycle;
	}
	
	
}
